import React, { useContext, useMemo, useEffect } from 'react'
import { Link } from 'react-router-dom'
import Counter from './Counter'

import { CartListContext } from '@/App'
export default function ProductDetail({ data }) {
  
  const { cartList, cartDispatch } = useContext(CartListContext)
  // 计算属性； 缓存当前商品的数量
  const currentCount = useMemo(() => cartList.find(item => item.id === data.id)?.count || 0, [data])
  
  return (
    <div>
      <h2>{ data.name }</h2>
      <p><img src={data.image} alt="" width={300} /></p>
      <p>{ data.desc }</p>
      <p>{ data.price }</p>
      <Counter 
        id={data.id} 
        currenCount={currentCount} 
        detail={ data }
        cartList={cartList} 
        cartListDispatch={cartDispatch}
        max={data.max_order}
      />
      <Link to="/cart">去购物车</Link>
    </div>
  )
}
